﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HySoft.Cash.BaseClass;
using HySoft.Cash.Business;
using HySoft.Cash.Structure;
using PayRoller.Code;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;
using Huayou.UI.WebControls;
using PayRoller.UControls;
using HySoft.Cash;

namespace PayRoller.Include
{
    public partial class UEmpPay : System.Web.UI.UserControl
    {
        // Fields
        protected Button Button1;
        protected Button Button2;
        protected Button Button3;
        protected Button Button4;
        protected Button Button5;
        protected Button Button6;
        protected CheckBox cbPayment;
        protected DropDownList dlAccount;
        protected DropDownList dlPayment;
        protected DropDownList dlPayment2;
        protected DropDownList dlStatus;
        public DataTable dtBankList;
        public string EmpName = "";
        public string EmpStatus = "";
        protected HtmlForm form1;
        protected Label lblTip;
        public string OrgEmpSid = "";
        public int OrgSid;
        protected RadioButtonList RadioButtonList1;
        protected ScriptManager ScriptManager1;
        public string Sid = "";
        protected HtmlTable TABLE1;
        protected HtmlTable TABLE2;
        protected HtmlTable TABLE3;
        protected HtmlTable TABLE4;
        protected HtmlTable TABLE5;
        protected HtmlTable TABLE6;
        protected TextBox txtAccountName;
        protected TextBox txtAccountName2;
        protected TextBox txtAccountNum;
        protected TextBox txtAccountNum2;
        protected TextBox txtAmount;
        protected TextBox txtBankName;
        protected TextBox txtBankName2;
        protected TextBox txtBranch;
        protected TextBox txtBranch2;
        protected TextBox txtBsb;
        protected TextBox txtBsb2;
        protected TextBox txtPaymentAmount;
        protected TXTFormatDate txtPaymentDate;
        protected TextBox txtPayReference;
        protected TextBox txtPayReference2;
        protected Literal litAmountTip;
        protected HtmlAnchor btnReturn;
        protected TextBox txtReferenceInfo;

        private int lockDayCountBeforePayDate = 0;
        /// <summary>
        /// 工资日提前N天锁定记录
        /// </summary>
        public int LockDayCountBeforePayDate
        {
            get
            {
                return lockDayCountBeforePayDate;
            }
            set
            {
                lockDayCountBeforePayDate = value;
            }
        }

        /// <summary>
        /// 点击页面上的Return按钮时，返回的页面
        /// </summary>
        public string ReturnUrl { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Button1.Attributes.Add("onclick", "return Check1();");
            this.Button2.Attributes.Add("onclick", "return Check2();");
            this.Button3.Attributes.Add("onclick", "return Check3();");
            this.Button4.Attributes.Add("onclick", "return Check4();");
            if (base.Request["EmpSid"] != null)
            {
                try
                {
                    TempinfoBN obn = new TempinfoBN(this.Page);
                    TempinfoDT odt = obn.Get(Convert.ToInt32(base.Request["EmpSid"].ToString()));
                    this.OrgSid = odt.OrgSid;
                    this.Sid = odt.Sid.ToString();
                    this.OrgEmpSid = odt.OrgEmpSid;
                    this.EmpName = odt.EmpName;
                    this.EmpStatus = odt.IsValid.ToString();
                    if (this.EmpStatus.Trim().Equals("1"))
                    {
                        this.EmpStatus = "Active";
                    }
                    else
                    {
                        this.EmpStatus = "Terminated";
                    }
                    obn.Dispose();
                    obn = null;
                }
                catch (Exception exception)
                {
                    this.lblTip.Text = exception.Message;
                }
                if (!this.Page.IsPostBack)
                {
                    this.GetBankInfo();
                    this.litAmountTip.Text = string.Format("(MaxValue:{0})", this.GetAvaliableCredit(OrgSid).ToString());
                }
                this.dtBankList = this.GetBankList();
            }
            if (!this.Page.IsPostBack)
            {
                SetUnVisibleTable();
                if (string.IsNullOrEmpty(this.ReturnUrl) == false)
                {
                    this.btnReturn.HRef = this.ReturnUrl;
                }
                else
                {
                    this.btnReturn.HRef = string.Format("~/Member/EmpDetail.aspx?OrgSid={0}&Sid={1}", this.OrgSid, this.Sid);
                }
            }
            if (base.Request["BankSid"] != null)
            {
                SetUnVisibleTable();
                this.TABLE6.Visible = true;
                if (!this.Page.IsPostBack)
                {
                    TbankinfoBN obn2 = new TbankinfoBN(this.Page);
                    TbankinfoDT odt2 = obn2.Get(Convert.ToInt32(base.Request["BankSid"]));
                    this.txtBankName2.Text = odt2.BankName;
                    this.txtBranch2.Text = odt2.Branch;
                    this.txtAccountName2.Text = odt2.AccountName;
                    this.txtAccountNum2.Text = odt2.AccountNum;
                    this.txtBsb2.Text = odt2.Bsb;
                    this.txtPayReference2.Text = odt2.PayReference;
                    obn2.Dispose();
                    obn2 = null;
                }
            }

            this.txtPaymentDate.StartDate = SafeDateTime.LocalToday.AddDays(1); //DateTime.Today;
        }

        private void SetUnVisibleTable()
        {
            this.TABLE1.Visible = false;
            this.TABLE2.Visible = false;
            this.TABLE3.Visible = false; 
            this.TABLE4.Visible = false; 
            this.TABLE5.Visible = false;
            this.TABLE6.Visible = false;
        }

        // Methods
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (base.Request["EmpSid"] != null)
            {
                string str = base.Request["EmpSid"].ToString();
                int num = 0;
                if (this.cbPayment.Checked)
                {
                    SqlParameter[] commandParameters = new SqlParameter[] { new SqlParameter("@pSid", this.dlPayment.SelectedValue), new SqlParameter("@pEmpSid", str), new SqlParameter("@pPaymentAmount", this.txtAmount.Text), new SqlParameter("@pIsFuture", 1) };
                    num = SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["SQLConnString"], CommandType.StoredProcedure, "UpdateEmpAmount", commandParameters);
                }
                else
                {
                    SqlParameter[] parameterArray2 = new SqlParameter[] { new SqlParameter("@pSid", this.dlPayment.SelectedValue), new SqlParameter("@pEmpSid", str), new SqlParameter("@pPaymentAmount", this.txtAmount.Text), new SqlParameter("@pIsFuture", SqlDbType.BigInt) };
                    num = SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["SQLConnString"], CommandType.StoredProcedure, "UpdateEmpAmount", parameterArray2);
                }
                if (num > 0)
                {
                    new OpeCommon().AddUptReport(Convert.ToInt32(str), "0006", this.OrgSid);
                    this.Page.ClientScript.RegisterStartupScript(base.GetType(), "", "<script>alert('Success!');</script>");
                    this.GetPaymentInfo();
                }

                this.SetUnVisibleTable();
            }
        }

        protected void Button2_Click(object sender, EventArgs e)
        {


            bool isCorrectDateFormat = false;
            //------20090608将账单日期 转换成数据库中期望的日期---------------------------------------------------
            string tempPayDate = this.txtPaymentDate.Text;

            DateTime payDateInDB = new DateTime();
            try
            {
                payDateInDB = Convert.ToDateTime(tempPayDate, AppSettings.DataBaseCulture);
                isCorrectDateFormat = true;
            }
            catch
            {
                isCorrectDateFormat = false;
            }

            if (payDateInDB < SafeDateTime.LocalToday.AddDays(1))
            {
                this.lblTip.Text = "Payment date must be later than today";
            }
            else
            {
                //string payDateConverted = string.Empty;
                ////Alert alert = new Alert(this.Page);
                //if (tempPayDate == string.Empty)
                //{
                //    //alert.Response("please confirm your Date");
                //    return;
                //}
                //else
                //{
                //    string[] temps = tempPayDate.Split('/', '-');
                //    if (temps.Length < 3)
                //    {
                //        //alert.Response("please confirm your Date");
                //        return;
                //    }
                //    else
                //    {
                //        payDateConverted = string.Format("{0}/{1}/{2}", temps[2], temps[1], temps[0]);
                //        try
                //        {
                //            Convert.ToDateTime(payDateConverted);
                //        }
                //        catch
                //        {
                //            //alert.Response("please confirm your Date");
                //            return;
                //        }
                //    }
                //}
                //---------------------------------------------------------------------------------------------------

                if ((base.Request["EmpSid"] != null) && (this.dlAccount.SelectedValue != "") && (isCorrectDateFormat == true))
                {
                    int empSid = Convert.ToInt32(base.Request["EmpSid"]);
                    int bankSid = Convert.ToInt32(this.dlAccount.SelectedValue);


                    try
                    {
                        decimal payAmount = Convert.ToDecimal(this.txtPaymentAmount.Text);
                        if (payAmount > Convert.ToDecimal(GetAvaliableCredit(OrgSid)))
                        {
                            this.Page.ClientScript.RegisterStartupScript(base.GetType(), "", "<script>alert('Fail,the pay amount cannot be greater than maxvalue!');</script>");
                        }
                        else
                        {
                            TemppaymentBN tbn = new TemppaymentBN(this.Page);

                            //运行给员工添加payment的规则，由原来的 有未处理的payment不能生产新的payment，
                            // 变为 a)	如果员工所在的企业，有应付而未付的 Invoice那么，就不允许给这个员工生成新的payment了
                            //      b)	如果员工所在的企业，没有应付的Invoice，那么是允许为这个员工生成新的payment的
                            /*
                            tbn.QueryEmpSid(empSid);
                            tbn.QueryBankSid(bankSid);
                            tbn.QueryInvoiceStatus(PaymentStatuses.NeedDeal);
                             */

                            //if (tbn.GetList().Rows.Count <= 0)
                            int overDueInvoiceCount = TinvoicelistBN.GetOverDueInvoiceCount(this.OrgSid);
                            if (overDueInvoiceCount <= 0)
                            {
                                TemppaymentDT detail = new TemppaymentDT();
                                detail.EmpSid = empSid;
                                detail.BankSid = bankSid;
                                detail.OrgSid = this.OrgSid;
                                detail.PaymentDate = payDateInDB;//Convert.ToDateTime(payDateConverted);
                                detail.PaymentAmount = payAmount;
                                detail.ReferenceInfo = this.txtReferenceInfo.Text;
                                if (tbn.Add(detail))
                                {
                                    new OpeCommon().AddUptReport(empSid, "0002", this.OrgSid);
                                }
                                tbn.Dispose();
                                tbn = null;
                                this.Page.ClientScript.RegisterStartupScript(base.GetType(), "", "<script>alert('Success!');</script>");
                                this.txtPaymentDate.Text = this.txtPaymentAmount.Text = "";

                                this.SetUnVisibleTable();
                            }
                            else
                            {
                                this.Page.ClientScript.RegisterStartupScript(base.GetType(), "", "<script>alert('failure,still has opening invoice(s)!');</script>");
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        this.lblTip.Text = exception.Message;
                    }
                }
                else
                {
                    this.Page.ClientScript.RegisterStartupScript(base.GetType(), "", "<script>alert('please confirm the date format you inputted!');</script>");
                }
            }
        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            TemppaymentBN tbn = new TemppaymentBN(this.Page);
            if (tbn.Delete(Convert.ToInt32(this.dlPayment2.SelectedValue)))
            {
                new OpeCommon().AddUptReport(Convert.ToInt32(base.Request["EmpSid"]), "0005", this.OrgSid);
                this.Page.ClientScript.RegisterStartupScript(base.GetType(), "", "<script>alert('Success!');</script>");
            }
            tbn.Dispose();
            tbn = null;
            this.GetPaymentInfo();
            this.SetUnVisibleTable();
        }

        protected void Button4_Click(object sender, EventArgs e)
        {
            TbankinfoBN obn = new TbankinfoBN(this.Page);
            TbankinfoDT detail = new TbankinfoDT();
            detail.EmpSid = Convert.ToInt32(base.Request["EmpSid"]);
            detail.BankName = this.txtBankName.Text;
            detail.Branch = this.txtBranch.Text;
            detail.AccountName = this.txtAccountName.Text;
            detail.AccountNum = this.txtAccountNum.Text;
            detail.Bsb = this.txtBsb.Text;
            detail.PayReference = this.txtPayReference.Text;
            obn.Add(detail);
            obn.Close();
            obn.Dispose();
            this.txtBankName.Text = "";
            this.txtBranch.Text = "";
            this.txtAccountName.Text = "";
            this.txtAccountNum.Text = "";
            this.txtBsb.Text = "";
            this.txtPayReference.Text = "";
            this.Page.ClientScript.RegisterStartupScript(base.GetType(), "", "<script>alert('Success!');</script>");
            this.GetBankInfo();
            this.SetUnVisibleTable();
        }

        protected void Button5_Click(object sender, EventArgs e)
        {
            TempinfoBN obn = new TempinfoBN(this.Page);
            TempinfoDT detail = obn.Get(Convert.ToInt32(base.Request["EmpSid"]));
            detail.IsValid = Convert.ToInt32(this.dlStatus.SelectedValue);
            obn.Edit(detail);
            this.Page.ClientScript.RegisterStartupScript(base.GetType(), "", "<script>alert('Success!');</script>");
            obn.Dispose();
            obn = null;

            this.SetUnVisibleTable();
        }

        protected void Button6_Click(object sender, EventArgs e)
        {
            if (base.Request["BankSid"] != null)
            {
                TbankinfoBN obn = new TbankinfoBN(this.Page);
                TbankinfoDT detail = obn.Get(Convert.ToInt32(base.Request["BankSid"]));
                detail.EmpSid = Convert.ToInt32(base.Request["EmpSid"]);
                detail.BankName = this.txtBankName2.Text;
                detail.Branch = this.txtBranch2.Text;
                detail.AccountName = this.txtAccountName2.Text;
                detail.AccountNum = this.txtAccountNum2.Text;
                detail.Bsb = this.txtBsb2.Text;
                detail.PayReference = this.txtPayReference2.Text;
                obn.Edit(detail);
                obn.Dispose();
                obn = null;
                this.Page.ClientScript.RegisterStartupScript(base.GetType(), "", "<script>alert('Success!');</script>");
                this.dtBankList = this.GetBankList();
                this.GetBankInfo();

                this.SetUnVisibleTable();
            }
        }

        public void GetBankInfo()
        {
            this.dlAccount.Items.Clear();
            TbankinfoBN obn = new TbankinfoBN(this.Page);
            obn.QueryEmpSid(Convert.ToInt32(base.Request["EmpSid"]));
            DataTable list = obn.GetList();
            ListItem item = null;
            for (int i = 0; i < list.Rows.Count; i++)
            {
                item = new ListItem(list.Rows[i]["Bsb"].ToString() + " - " + list.Rows[i]["AccountNum"].ToString(), list.Rows[i]["Sid"].ToString());
                this.dlAccount.Items.Add(item);
            }
            obn.Dispose();
            obn = null;
        }

        public DataTable GetBankList()
        {
            TbankinfoBN obn = new TbankinfoBN(this.Page);
            obn.QueryEmpSid(Convert.ToInt32(base.Request["EmpSid"]));
            DataTable list = obn.GetList();
            obn.Dispose();
            obn = null;
            return list;
        }

        /// <summary>
        /// 获取某企业当前的实时可用额度
        /// </summary>
        /// <param name="orgSid"></param>
        /// <returns></returns>
        private double GetAvaliableCredit(int orgSid)
        {
            double result = GetTotalCredit(orgSid) - TorginfoBN.GetRealTimeCreditBalance(orgSid);
            return result;
        }

        /// <summary>
        /// 获取某企业总的授信额度（包含溢缴部分）
        /// </summary>
        /// <param name="orgSid"></param>
        /// <returns></returns>
        private double GetTotalCredit(int orgSid)
        {
            return GetTotalCredit(orgSid,true);
        }

        /// <summary>
        /// 获取某企业总的授信额度
        /// </summary>
        /// <param name="orgSid"></param>
        /// <param name="isIncludeOverPrice"></param>
        /// <returns></returns>
        private double GetTotalCredit(int orgSid,bool  isIncludeOverPrice)
        {
            using (TorginfoBN obn = new TorginfoBN(this.Page))
            {
                TorginfoDT odt = obn.Get(OrgSid);
                double result = 0;
                if (isIncludeOverPrice == true)
                {
                    result = Convert.ToDouble(odt.CreditLimit + odt.RemainBalance);
                }
                else
                { 
                    result=  Convert.ToDouble(odt.CreditLimit);
                }
                return result;
            }
        }

        public void GetPaymentInfo()
        {
            this.dlPayment.Items.Clear();
            this.dlPayment2.Items.Clear();
            TemppaymentBN tbn = new TemppaymentBN(this.Page);
            tbn.QueryEmpSid(Convert.ToInt32(base.Request["EmpSid"]));
            //--已经生成Invoice的payment不能被修改了，需要过滤掉;而只显示还未处理的payment--------------
            tbn.QueryInvoiceStatus(PaymentStatuses.NeedDeal);
            if (this.lockDayCountBeforePayDate > 0)
            {
                tbn.Filter = string.Format("[PaymentDate]<='{0}'", SafeDateTime.LocalToday.AddDays(-lockDayCountBeforePayDate));
            }
            //------------------------------------------------------------------------------------------
            DataTable list = tbn.GetList();
            ListItem item = null;
            for (int i = 0; i < list.Rows.Count; i++)
            {
                string[] strArray = new string[] { "#", (i + 1).ToString(), "[", Convert.ToDateTime(list.Rows[i]["PaymentDate"]).ToString(AppSettings.DateFormatAU), "]", list.Rows[i]["PaymentAmount"].ToString() };
                item = new ListItem(string.Concat(strArray), list.Rows[i]["Sid"].ToString());
                this.dlPayment.Items.Add(item);
                this.dlPayment2.Items.Add(item);
            }
            this.dlPayment.Items.Insert(0, new ListItem("Please Select Your Payment", "-1"));
            this.dlPayment2.Items.Insert(0, new ListItem("Please Select Your Payment", "-1"));

            tbn.Dispose();
            tbn = null;
        }

        protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selectedValue = this.RadioButtonList1.SelectedValue;
            if (selectedValue != null)
            {
                if (!(selectedValue == "0"))
                {
                    if (!(selectedValue == "1"))
                    {
                        if (!(selectedValue == "2"))
                        {
                            if (!(selectedValue == "3"))
                            {
                                if (!(selectedValue == "4"))
                                {
                                    if (selectedValue == "5")
                                    {
                                        this.TABLE6.Visible = true;
                                        this.TABLE2.Visible = this.TABLE3.Visible = this.TABLE1.Visible = this.TABLE5.Visible = this.TABLE4.Visible = false;
                                    }
                                    return;
                                }
                                this.TABLE5.Visible = true;
                                this.TABLE2.Visible = this.TABLE3.Visible = this.TABLE4.Visible = this.TABLE1.Visible = this.TABLE6.Visible = false;
                                return;
                            }
                            this.TABLE4.Visible = true;
                            this.TABLE2.Visible = this.TABLE3.Visible = this.TABLE1.Visible = this.TABLE5.Visible = this.TABLE6.Visible = false;
                            return;
                        }
                        this.GetPaymentInfo();
                        this.TABLE3.Visible = true;
                        this.TABLE2.Visible = this.TABLE1.Visible = this.TABLE4.Visible = this.TABLE5.Visible = this.TABLE6.Visible = false;
                        return;
                    }
                }
                else
                {
                    this.GetPaymentInfo();
                    this.TABLE1.Visible = true;
                    this.TABLE2.Visible = this.TABLE3.Visible = this.TABLE4.Visible = this.TABLE5.Visible = this.TABLE6.Visible = false;
                    return;
                }
                this.TABLE2.Visible = true;
                this.TABLE1.Visible = this.TABLE3.Visible = this.TABLE4.Visible = this.TABLE5.Visible = this.TABLE6.Visible = false;
            }
        }


        protected void dlPayment_SelectedIndexChanged(object sender, EventArgs e)
        {
            PaymentSelectedIndexChanged(sender, this.Button1);
        }

        protected void dlPayment2_SelectedIndexChanged(object sender, EventArgs e)
        {
            PaymentSelectedIndexChanged(sender, this.Button3);
        }

        private void PaymentSelectedIndexChanged(object sender, WebControl control)
        {
            /*
             * 在生成payment列表时，就已经过滤掉了，不能修改的payment，因此此处代码可以不再使用
             */

            //DropDownList ddl = sender as DropDownList;
            //if (ddl != null)
            //{
            //    string ddlText = ddl.SelectedItem.Text;
            //    int posBegin = ddlText.IndexOf("[") + 1;
            //    int posEnd = ddlText.IndexOf("]");
            //    try
            //    {
            //        DateTime paymentDate = Convert.ToDateTime(ddlText.Substring(posBegin, posEnd - posBegin), AppSettings.CurrentCulture);
            //        if (paymentDate < new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day).AddDays(this.LockDayCountBeforePayDate))
            //        {
            //            control.Enabled = false;
            //            this.lblTip.Text = "Current payment cann't be modified.";
            //            this.lblTip.Visible = true;
            //        }
            //        else
            //        {
            //            control.Enabled = true;
            //            this.lblTip.Visible = false;
            //        }
            //    }
            //    catch
            //    {
            //        control.Enabled = false;
            //        this.lblTip.Text = "Please select your payment.";
            //        this.lblTip.Visible = true;
            //    }
            //}
        }
    }
}